package com.chen.project.white_jotter.service.admin;

import com.chen.project.white_jotter.mapper.AdminMenuMapper;
import com.chen.project.white_jotter.pojo.AdminMenu;
import com.chen.project.white_jotter.pojo.User;
import com.chen.project.white_jotter.service.UserService;
import com.chen.project.white_jotter.utils.SecurityUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.List;

@Service
public class MenuService {

    @Resource
    private UserService userService;

    @Resource
    private UserRoleService userRoleService;

    @Resource
    private RoleMenuService roleMenuService;

    @Resource
    private AdminMenuMapper adminMenuMapper;

    public List<AdminMenu> getMenuListByCurrentUser(){

        // 从 security 上下文中获取当前用户
        String username = SecurityUtil.getCurrentUsername();
        User user = userService.getUserByUsername(username);

        // 查询当前用户对应的角色
        Integer rolesId = userRoleService.getRoleIdByUserId(user.getId());
        // 查询这些角色对应的菜单项的id
        List<Integer> menuIds = roleMenuService.getAllMenusByRolesId(rolesId);

        // 查询这些角色对应的菜单项
        List<AdminMenu> menus = adminMenuMapper.selectAllMenusByMenusId(menuIds);

        // 处理成树结构
        handleMenus(menus, menuIds);

        return menus;
    }

    // 把角色对应的菜单选项组织成树结构
    public void handleMenus(List<AdminMenu> menus, List<Integer> menuIds){

        for(AdminMenu menu:menus){
            List<AdminMenu> childrenMenus = adminMenuMapper.selectChildrenMenusByParentId(menu.getId(), menuIds);
            menu.setChildren(childrenMenus);
        }

        Iterator<AdminMenu> iterator = menus.iterator();
        while (iterator.hasNext()) {
            AdminMenu menu = iterator.next();
            if (menu.getParentId() != 0) {
                iterator.remove();
            }
        }

        // menus.forEach(m -> {
        //     List<AdminMenu> children = adminMenuMapper.selectChildrenMenusByParentId(m.getId());
        //     m.setChildren(children);
        // });
        //
        // menus.removeIf(m -> m.getParentId() != 0);
    }
}
